<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */
namespace App\Service\Api;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\DbConnection\Db;
use App\Utils\ServerUtil;
use App\Lib\UploadFile;
use App\Dao\UploadDao;
use App\Utils\Redis;
use Hyperf\Utils\ApplicationContext;

class UploadService
{

    /**
     * @Inject
     * @var UploadDao
     */
    protected $dao;

    public function upload($file, $user)
    {
        $md5 = md5_file($file->getRealPath());
        $upload = new UploadFile();
        $file_info = $upload->getFileInfo($file);
        //先判断是否存在
        $where = [];
        $where[] = ['md5','=',$upload->getFilemd5()];
        $where[] = ['content_type','=',$upload->getMimeType()];
        $res = $this->dao->searchFirst($where);
        if ($res) {
            return $res->toArray();
        }
        $result = $upload->uploadFile($file);
        $data['user_id'] = $user['id'] ?? 1;
        $data['user_name'] = $user['name'] ?? 1;
        $data['md5'] = $upload->getFilemd5();
        $data['file_path'] = $upload->getPath();
        $data['content_type'] = $upload->getMimeType();
        $data['chunk_size'] = $upload->getSize();
        $data['origin_name'] = $upload->getFileName();
        $id = $this->dao->add($data);
        return ['id'=>$id,'origin_name'=>$data['origin_name'],'chunk_size'=>$data['chunk_size'],'user_name'=>$data['user_name'],'file_path'=>env('WEB_HOST', '127.0.0.1:9501').'/'.$data['file_path']];
    }
}
